<template>
  <div class="app-container">
    <el-button   class="filter-item marginRB10" type="success" @click="handleCreate()">&emsp;新增&emsp;</el-button>
    <el-button class="marginRB10" type="danger" @click="allDel()">批量删除</el-button>

    <el-date-picker class="marginRB10" v-model="listQuery.add_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择添加时间"></el-date-picker>
    <el-input class="marginRB10" v-model="listQuery.good_number" placeholder="请输入靓号" style="width:200px;"
              clearable></el-input>
    <!-- <el-select filterable v-model="listQuery.type" class="filter-item marginRB10" placeholder='请选择获取途径' style="width: 200px;">
      <el-option v-for="item in selectList2" :key="item.key" :label="item.lab" :value="item.key"></el-option>
    </el-select> -->
    <el-button type="primary" @click="getList" icon="el-icon-search"   class="marginRB10">搜索</el-button>


    <el-table ref="dataList" :data="menuList" style="margin-bottom: 20px;" row-key="id" border
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="序号"></el-table-column>
      <el-table-column prop="good_number" label="靓号编号"></el-table-column>
      <el-table-column prop="user_code" label="原始编号"></el-table-column>
      <el-table-column prop="status" label="使用状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success">使用中</el-tag>
          <el-tag v-if="scope.row.status === 0" type="warning">未发放</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="rebate" label="发放途径" > </el-table-column> -->
      <el-table-column prop="nickname" label="用户昵称"></el-table-column>
      <el-table-column prop="expired_time" label="使用截止时间"></el-table-column>
      <el-table-column prop="add_time" label="添加时间"></el-table-column>
      <!-- <el-table-column prop="" label="操作人" > </el-table-column> -->
      <el-table-column prop="remark" label="备注"></el-table-column>

      <el-table-column min-width="180" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)" plain>编辑
          </el-button>
          <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.perPage"
                    @pagination="getList"/>

    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible"
               @close="handleDialogClose">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="120px"
               style="width: 400px; margin: 0 auto;">
        <el-form-item label="靓号" prop="good_number">
          <el-input v-model.number="form.good_number" placeholder="请输入靓号"/>
        </el-form-item>
        <el-form-item label='过期时间' prop="expired_time">
          <el-date-picker
            v-model="form.expired_time"
            type="datetime"
            placeholder="选择日期时间(不选默认为永久)">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="类型" prop="cate_id">
          <el-select filterable v-model="form.cate_id" class="filter-item" placeholder='请选择类型'>
            <el-option v-for="item in selectList2" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='备注' prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" type="textarea"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {deleteData, listData, getCateList} from '@/api/goodNumber/goodNumberList'

export default {
  data() {
    return {
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10,
        add_time: undefined,
        good_number: undefined
      },
      menuList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      titleMap: {
        update: '编辑',
        create: '增加'
      },
      selectList2: [],
      form: {
        good_number: undefined,
        cate_id: undefined,
        expired_time: undefined,
        remark: undefined
      },
      rules: {
        good_number: [{type: 'number', required: true, message: '请输入靓号', trigger: 'blur'}],
        cate_id: [{type: 'number', required: true, message: '请选择靓号分类', trigger: 'change'}],
        expired_time: [{required: false, message: '请选择过期时间', trigger: 'change'}],
        remark: [{required: false, message: '请输入备注', trigger: 'blur'}],
      }
    }
  },
  created() {
    this.getList()
    this.getCateList()
  },
  methods: {
    getList() {
      this.listLoading = true
      let urlData = '?'
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`;
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`;
      }
      if (this.listQuery.add_time) {
        urlData = urlData + `&add_time=${this.listQuery.add_time}`;
      }
      if (this.listQuery.good_number) {
        urlData = urlData + `&good_number=${this.listQuery.good_number}`;
      }
      listData(urlData).then(response => {

        this.menuList = response.data.list
        this.listLoading = false
      })
    },
    // 获取靓号分类列表
    getCateList() {
      getCateList().then(response => {
        response.data.list.forEach(item => {
          let obj = {}
          for (let key in item) {
            if (key === 'id') {
              obj['value'] = item[key]
            } else if (key === 'name') {
              obj['label'] = item[key]
            }
          }
          this.selectList2.push(obj)
        })
      })
    },
    handleCreate(row) {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      // this.form = []

      this.form.good_number = row.good_number
      this.form.cate_id = row.cate_id
      this.form.expired_time = row.expired_time
      this.form.remark = row.remark

      this.dialogStatus = 'update'
      this.dialogFormVisible = true

      // this.form = Object.assign({}, this.form)
    },
    handleDelete(row) {
      let data = {ids: row.id}
      deleteData(data).then(response => {
        if (response.code === 200) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          });
        }
      })
    },
    allDel() {

      let delNum = []
      this.$refs.dataList.selection.forEach((k) => {
        delNum.push(k.id)
      })
      if (delNum.length === 0) {
        return;
      }
      let data = {ids: delNum.toString()}
      deleteData(data).then(response => {
        if (response.code === 200) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          });
        }
      })
    },
    submitForm() {
      this.$refs['dataForm'].validate(valid => {
        if (valid && this.dialogStatus === 'create') {
          if (this.form.expired_time !== undefined) {
            let t = new Date(this.form.expired_time).getTime().toString()
            t = parseInt(t.substring(0, t.length - 3));
            this.form.expired_time = t
          } else {
            this.form.expired_time = 0
          }

          let formData = new FormData();
          for (let item in this.form) {
            this.form[item] === undefined ? '' : formData.append(item, this.form[item]);
          }
          saveData(formData).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              });
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              });
            }
          })
        } else if (valid && this.dialogStatus === 'update') {
          let formData = new FormData();
          for (let item in this.form) {
            this.form[item] === undefined ? '' : formData.append(item, this.form[item]);
          }
          updateData(formData).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              });
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              });
            }
          })
        }
      })
    },
    resetForm() {
      this.form = {
        good_number: undefined,
        cate_id: undefined,
        expired_time: undefined,
        remark: undefined
      }
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
      }
    }
  }
}
</script>
